package com.lmonkey.filter;

import com.lmonkey.dao.Basedao;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebFilter("/shangc/regrxx")
public class Regrxx implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest reqq = (HttpServletRequest)req;
        HttpServletResponse respp = (HttpServletResponse) resp;
        //设置字符集
        reqq.setCharacterEncoding("UTF-8");
        respp.setContentType("text/html;charset=utf-8");

        String username = reqq.getParameter("username");
        String yname = reqq.getParameter("yname");

        PrintWriter out = respp.getWriter();
        //验证用户名是否为空
        if (username.equals("")){
            out.println("<script>alert('用户名不能为空');location.href='/lyq/shangc/mygrxxselect';</script>");
            out.close();
            return;
        }else {
            Pattern pt = Pattern.compile("[a-zA-Z\\u4E00-\\u9FA5]*");
            Matcher mt = pt.matcher(username);
            if (!mt.matches()){
                out.println("<script>alert('姓名格式不正确');location.href='/lyq/shangc/mygrxxselect';</script>");
                out.close();
                return;
            }else {
                if (!yname.equals(username)){
                    Connection conn = Basedao.getconn();
                    PreparedStatement ps = null;
                    ResultSet rs = null;
                    int count = 0;
                    try {
                        String sql = "select count(*) from lmonkeyshop where user_id = ? ";
                        ps = conn.prepareStatement(sql);
                        ps.setObject(1,username);
                        rs = ps.executeQuery();
                        while(rs.next()){
                            count = rs.getInt(1);
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    if (count>0){
                        out.println("<script>alert('该姓名已存在');location.href='mygrxxselect';</script>");
                        out.close();
                        return;
                    }
                }
            }
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
